/*A main program to test EvtData Interface
 * 
 * 
 Users should !!!only!!! edit EvtData::FillEvtData
 when migrating to a new tree structure. minimal knowledge of 
 the tree structure is required
 
 To do's : 
 
 1)BaseClass EvtData (done) all tree classes shall inherit from it 
    Delphes Tre and D3P3 tree formatas are implemented
 2) BaseClass Analysis (done) all analysis classes shall inherit from it
    E6 Analysis class is implemented

 3) modify the code to run on grid 
    still to do
 4) Any more ideas?
 
 */

/*
 Author : 	Serhat Istin
 
 Bogazici University Physics Department
 
 e-mail	:	istin@cern.ch
 
 
 */


#include "d3pdrel16.h"
#include "E6ANA.h"
#include "TTree.h"
#include <iostream>
#include <fstream>
#include <map>
#include "Run.h"
#include "TStopwatch.h"
#include "TH1F.h"


int main(int argc, char *argv[]){
	//check for proper input arguments exit if not supplied
	
	if(argc!=4){
		std::cout<<"--------USAGE------"<<std::endl;
		std::cout<<"./e6analysis <inputRootFile> <Run.cfg> <outputRootFile>"<<std::endl;
		std::cout<<"-------------------"<<std::endl;
		exit(8);
		}


  TTree* atree;
  TFile *infile= TFile::Open(TString(argv[1]),"READ");
    infile->GetObject("Physics",atree);
  if(atree!=NULL){
  std::cout<<"Read physics from the file"<<std::endl;
  }
  else{
   std::cout<<"Error reading input file ..."<<std::endl;
   exit(-8);
  }  
EvtData* evtdata=new d3pdrel16(atree);

  
  Run* myrun = new Run();
  myrun->ParseRunargv[2]);
  myrun->ConfigureAnalyses();
  int Nevents;
  if(myrun->nevents<0) Nevents=atree->GetEntries();
  else Nevents=myrun->nevents;
  TStopwatch timer;
  TH1F* perf_hist=new TH1F("perf_hist","time of execution",1000,0,100);
  
  for( unsigned int ievt=0;ievt<Nevents;ievt++){//event loop
	if( ievt%10000==0){
		std::cout<<"Processing event: "<<ievt<<std::endl;
		}
    evtdata->FillEvtData(ievt);
    //clock start 
    timer.Start();
	myrun->RunAnalyses(evtdata);
	timer.Stop();
	perf_hist->Fill(timer.RealTime()*1E6);
	//std::cout<<"time of execution :"<<timer.RealTime()<<std::endl;
    //clock end 
    
    //Fill timer histogram
    evtdata->ClearEvtData();

  }//endof event loop

TFile *pf = new TFile("performance.root","RECREATE");
perf_hist->Write();
pf->Close();
delete pf;

ifstream roofile(argv[3]);

if(roofile){
std::cout<<"Output File Already Exists.... Removing the previous file"<<std::endl;

  if(remove(argv[3])!=0){
		std::cout<<"Cannot remove previous File"<<std::endl;
		
		
	}
	else{
		std::cout<<"Deleted Previous File"<<std::endl;
	}
}


myrun->Finalize(TString(argv[3]));


std::cout<<"Results written to the file : "<<argv[3]<<std::endl;
return 0;
}
